﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.TemplateLanguage.Properties;

namespace MethodWorx.CMS.TemplateLanguage
{
    public static class ParserPropertyHelper
    {
        public static TAttr GetPropertyAttribute<TAttr>(Type type, string name)
            where TAttr: PropertyAttribute
        {

            foreach(var property in type.GetProperties())
            {
                var pa = property.GetCustomAttributes(true);
                if(pa.Any())
                {
                    var attr = pa.OfType<TAttr>().FirstOrDefault();
                    if(attr != null)
                    {
                        if (property.Name.ToLower() == name.ToLower() || attr.Alias.ToLower() == name.ToLower())
                        {
                            attr.OriginalName = property.Name;
                            return attr;
                        }
                    }
                }
            }

            return null;
        }

        public static IEnumerable<PropertyAttribute> GetPropertyAttributes(Type type)
        {

            foreach (var property in type.GetProperties())
            {
                var pa = property.GetCustomAttributes(true);
                if (pa.Any())
                {
                    foreach(var p in pa.OfType<PropertyAttribute>())
                    {
                        p.OriginalName = property.Name;
                        yield return p;
                    }
                }
            }
        }
    }
}
